package com.guxiuwei.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.guxiuwei.sys.common.Result;
import com.guxiuwei.sys.entity.User;
import com.guxiuwei.sys.entity.Worder;
import com.guxiuwei.sys.entity.Workers;
import com.guxiuwei.sys.mapper.WorderMapper;
import com.guxiuwei.sys.mapper.WorkersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 谷秀伟
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/sys/workers")
public class WorkersController {
    @Autowired
    private WorkersMapper workersMapper;

    @Autowired
    private WorderMapper worderMapper;

    //将workers对象存入数据库中
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('客户经理')")
    public Result<?> save(@RequestBody Workers workers){
        Workers res = workersMapper.selectOne(Wrappers.<Workers>
                lambdaQuery().eq(Workers::getOid, workers.getOid())
                              .eq(Workers::getIdnum,workers.getIdnum()));
        if (res != null){
            return Result.error("0","该用户已注册");
        } else {
//        System.out.println(user);
            QueryWrapper<Worder> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("oid")
                    .last("limit 1");
            Worder worder = worderMapper.selectOne(queryWrapper);
            workers.setOid(worder.getOid() + 1);
            workersMapper.insert(workers);
            return Result.success();
        }
    }

    //对前端传入的user对象的uid进行相关记录删除操作
    @DeleteMapping("/delete")
    @PreAuthorize("hasAuthority('客户经理')")
    public Result<?> delete(@RequestBody Workers workers){
        workersMapper.deleteById(workers);
        return Result.success();
    }

    @PutMapping ("/selectWorkers")
    public Result<?> selectWorkers(@RequestBody Worder worder){
        QueryWrapper<Workers> wrapper = new QueryWrapper<>();
        wrapper.eq("oid",worder.getOid());
        List<Workers> workersList = workersMapper.selectList(wrapper);
        return Result.success(workersList);
    }




}

